package com.nova.edc.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.nova.edc.dao.system.DeviceAirDao;
import com.nova.edc.model.system.DeviceAir;
import com.nova.edc.service.system.DeviceAirService;
import com.nova.frame.dao.buzz.query.Order;
import com.nova.frame.dao.buzz.query.Query;
import com.nova.frame.dao.criterion.Restrictions;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.module.filter.query.Filter;

public class DeviceAirServiceImpl implements DeviceAirService {

    @Autowired
    private DeviceAirDao deviceAirDao;

    @Override
    public List<DeviceAir> findAll() {
        return deviceAirDao.findAll();
    }

    @Override
    public List<DeviceAir> findByExample(DeviceAir deviceAir) {
        return deviceAirDao.findByExample(deviceAir);
    }

    @Override
    public PageList<DeviceAir> findPageDeviceAir(DeviceAir deviceAir,
                                                 Page page, String sord, String sidx) {
        Query<DeviceAir> query = deviceAirDao.query().add(
                Restrictions.eq("Scrapped", 0));
        query.addOrder(Order.custom(sidx, sord));
        Filter.addFilterCondition(query, deviceAir);
        return query.pageList(page);
    }

    @Override
    public DeviceAir getById(Integer id) {
        return deviceAirDao.getById(id);
    }

    @Override
    public DeviceAir getByCode(String aircode) {
        return deviceAirDao.query()
                .add(Restrictions.eq("t_device_air.AirCode", aircode)).get();
    }

    @Override
    public DeviceAir insert(DeviceAir deviceAir) {
        DeviceAir airCode = deviceAirDao.query().add(Restrictions.eq("AirCode", deviceAir.getAircode())).get();
        if (airCode != null) {
            return airCode;
        } else {
            return deviceAirDao.insert(deviceAir);
        }
    }

    @Override
    public int update(DeviceAir deviceAir) {
        return deviceAirDao.updateNotNull(deviceAir);
    }

    @Override
    public int deleteById(Integer id) {
        return deviceAirDao.deleteById(id);
    }

    @Override
    public boolean isExistCode(String airCode) {
        Query<DeviceAir> query = deviceAirDao.query().add(
                Restrictions.eq("t_device_air.AirCode", airCode));
        return query.list().size() > 0;
    }

    @Override
    public List<String> findCodeByList(List<DeviceAir> deviceAirs) {
        List<String> codes = new ArrayList<String>();
        for (int i = 0; i < deviceAirs.size(); i++) {
            codes.add(deviceAirs.get(i).getAircode());
        }
        return codes;
    }
}
